package com.axc.gallery2.view;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.axc.gallery2.R;
import com.axc.gallery2.Utils;
import com.axc.gallery2.dbhelper.NetPhotosInfo;
import com.axc.gallery2.net.AsyncPhotoLoader;
import com.axc.gallery2.view.ImageAdapter.ViewHolder;

public class NetPhotosGridViewAdapter extends BaseAdapter {

	private Context context;

	private AsyncPhotoLoader asyncPhotoLoader = new AsyncPhotoLoader();

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	private List<NetPhotosInfo> _netPhotosInfos;

	public List<NetPhotosInfo> get_netPhotosInfos() {
		return _netPhotosInfos;
	}

	public void set_netPhotosInfos(List<NetPhotosInfo> netPhotosInfos) {
		_netPhotosInfos = netPhotosInfos;
	}

	/**
	 * 取得图片
	 */
	List<SoftReference<View>> convertviewList = new ArrayList<SoftReference<View>>();
	@SuppressWarnings("unused")
	private int width;

	public void clearConvertView() {
		convertviewList.clear();
	}

	public NetPhotosGridViewAdapter(Context context,
			List<NetPhotosInfo> netPhotosInfos) {

		// System.out.println("size :" + netAlbumInfos.size());
		this.context = context;
		_netPhotosInfos = netPhotosInfos;
	}

	@SuppressWarnings("finally")
	public View getView(int position, View convertView, ViewGroup parent) {
		System.out.println("NetPhotosViewAdapter1");
		final ViewHolder viewHolder;
		try {
			convertView = convertviewList.get(position).get();
		} catch (IndexOutOfBoundsException e) {
			System.out.println("NetPhotosViewAdapter2");

			viewHolder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(
					R.layout.net_photos_item, null);
			convertView.setTag(viewHolder);
			viewHolder.imageView = (ImageView) convertView
					.findViewById(R.id.net_photos_image);

			final String s_url =_netPhotosInfos.get(position).getS_url();
			viewHolder.idTextView = (TextView) convertView
					.findViewById(R.id.net_photos_pid);
			viewHolder.idTextView.setText(_netPhotosInfos.get(position)
					.getPid());
			// 如果文件存在
			if (fileIsExists(_netPhotosInfos.get(position).getL_url())) {
				viewHolder.imageView.setImageBitmap(Utils.RelBmp(_netPhotosInfos.get(position).getL_url()));
			} else {
				// 从网络异步读取
				// 如果缓存过就会从缓存中取出图像，ImageCallback接口中方法也不会被执行
				asyncPhotoLoader.loadDrawable(
						_netPhotosInfos.get(position).getS_url(),
						new AsyncPhotoLoader.ImageCallback() {
							// 如果第一次加载url时下面方法会执行
							public void imageLoaded(Drawable imageDrawable) {
								viewHolder.imageView
								.setImageDrawable(imageDrawable);
								Drawable cacheImage=imageDrawable;
								if (cacheImage != null) {
									viewHolder.imageView.setImageDrawable(cacheImage);
									Bitmap bitmap = Utils.drawableToBitmap(cacheImage);
									// 把图片写入到本地文件。
									if (Utils.getExternalStorageState()) {
										File file = new File(Environment
												.getExternalStorageDirectory().getPath()
												+ "/DCIM/Gallery2/temp");
										if(!file.exists())
										{
											file.mkdirs();
										}

										String fileName = Environment
												.getExternalStorageDirectory().getPath()
												+ "/DCIM/Gallery2/temp/_"
												+ s_url.split("/")[s_url.split("/").length - 1];
										File tempFile = new File(fileName.substring(0, fileName.length()-4));
										if (!tempFile.exists()) { 
											try { 
												tempFile.createNewFile(); 
											} catch (Exception e3) { 
											} 
										} 

										try {
											FileOutputStream fileOutputStream = new FileOutputStream(
													tempFile);
											bitmap.compress(CompressFormat.JPEG, 100, fileOutputStream); 
											fileOutputStream.flush();  
											fileOutputStream.close();
										} catch (Exception e2) {
											// TODO: handle exception
										}

									}

									//回收资源
									if (bitmap!=null && !bitmap.isRecycled()){
										bitmap.recycle();
										bitmap = null;
									}
								}

							}
						});

				convertviewList.add(new SoftReference<View>(convertView));
				System.out.println("NetPhotosViewAdapter3");
			} }catch (Exception e) {
			} finally {

				return convertView;
			}
	}

	@Override
	public int getCount() {
		if (_netPhotosInfos != null) {
			return _netPhotosInfos.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	public void setGridviewSize(int w) {
		width = w;

	}

	private boolean fileIsExists(String filepathString) {
		File f = new File(filepathString);
		if (!f.exists()) {
			return false;
		}
		return true;
	}

}
